package com.beauty.order.service.impl;

import com.beauty.order.client.InventoryClient;
import com.beauty.order.client.LogisticsClient;
import com.beauty.order.entity.Order;
import com.beauty.order.result.Result;
import com.beauty.order.service.OrderIntegrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderIntegrationServiceImpl implements OrderIntegrationService {

    private final InventoryClient inventoryClient;
    private final LogisticsClient logisticsClient;

    @Override
    public boolean checkProductInventory(String productId, Integer quantity) {
        log.info("【订单服务】开始检查产品[{}]库存，需要数量: {}", productId, quantity);
        try {
            log.info("【订单服务】远程调用库存服务: GET /api/inventory/product/{}", productId);
            Result<?> result = inventoryClient.checkProductInventory(productId);
            if (result.getCode() != 200) {
                log.error("【订单服务】查询库存失败: {}", result.getMessage());
                return false;
            }

            // 提取库存数量和预留库存数量，检查可用库存是否充足
            Map<String, Object> data = (Map<String, Object>) result.getData();
            Integer availableQuantity = (Integer) data.get("availableQuantity");
            log.info("【订单服务】库存服务返回结果 - 产品[{}]可用库存: {}, 需求: {}, 是否充足: {}",
                    productId, availableQuantity, quantity, availableQuantity >= quantity);

            return availableQuantity >= quantity;
        } catch (Exception e) {
            log.error("【订单服务】查询库存异常", e);
            return false;
        }
    }

    @Override
    public boolean reserveInventory(String productId, Integer quantity) {
        log.info("【订单服务】开始预留产品[{}]库存，数量: {}", productId, quantity);
        try {
            log.info("【订单服务】远程调用库存服务: PUT /api/inventory/product/{}/reserve?quantity={}", productId, quantity);
            Result<?> result = inventoryClient.reserveStock(productId, quantity);
            if (result.getCode() != 200) {
                log.error("【订单服务】预留库存失败: {}", result.getMessage());
                return false;
            }
            log.info("【订单服务】产品[{}]库存预留成功，数量: {}", productId, quantity);
            return true;
        } catch (Exception e) {
            log.error("【订单服务】预留库存异常", e);
            return false;
        }
    }

    @Override
    public boolean releaseInventory(String productId, Integer quantity) {
        log.info("【订单服务】开始释放产品[{}]预留库存，数量: {}", productId, quantity);
        try {
            log.info("【订单服务】远程调用库存服务: PUT /api/inventory/product/{}/release?quantity={}", productId, quantity);
            Result<?> result = inventoryClient.releaseReservedStock(productId, quantity);
            if (result.getCode() != 200) {
                log.error("【订单服务】释放库存失败: {}", result.getMessage());
                return false;
            }
            log.info("【订单服务】产品[{}]预留库存释放成功，数量: {}", productId, quantity);
            return true;
        } catch (Exception e) {
            log.error("【订单服务】释放库存异常", e);
            return false;
        }
    }

    @Override
    public boolean reduceInventory(String productId, Integer quantity) {
        log.info("【订单服务】开始减少产品[{}]库存，数量: {}", productId, quantity);
        try {
            log.info("【订单服务】远程调用库存服务: PUT /api/inventory/product/{}/reduce?quantity={}", productId, quantity);
            Result<?> result = inventoryClient.reduceStock(productId, quantity);
            if (result.getCode() != 200) {
                log.error("【订单服务】减少库存失败: {}", result.getMessage());
                return false;
            }
            log.info("【订单服务】产品[{}]库存减少成功，数量: {}", productId, quantity);
            return true;
        } catch (Exception e) {
            log.error("【订单服务】减少库存异常", e);
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> getAvailableCarriers() {
        log.info("【订单服务】获取可用承运商列表");
        try {
            // 假设物流服务有一个获取可用承运商的接口
            Result<?> result = logisticsClient.getAvailableCarriers();
            if (result.getCode() != 200) {
                log.error("【订单服务】获取可用承运商列表失败: {}", result.getMessage());
                return new ArrayList<>();
            }
            
            List<Map<String, Object>> carriers = (List<Map<String, Object>>) result.getData();
            log.info("【订单服务】获取到{}个可用承运商", carriers.size());
            return carriers;
        } catch (Exception e) {
            log.error("【订单服务】获取可用承运商列表异常", e);
            // 返回默认的承运商列表，避免前端显示空白
            List<Map<String, Object>> defaultCarriers = new ArrayList<>();
            
            Map<String, Object> sf = new HashMap<>();
            sf.put("code", "SF");
            sf.put("name", "顺丰快递");
            defaultCarriers.add(sf);
            
            Map<String, Object> zto = new HashMap<>();
            zto.put("code", "ZTO");
            zto.put("name", "中通快递");
            defaultCarriers.add(zto);
            
            Map<String, Object> yto = new HashMap<>();
            yto.put("code", "YTO");
            yto.put("name", "圆通快递");
            defaultCarriers.add(yto);
            
            return defaultCarriers;
        }
    }

    @Override
    public boolean createShipment(Order order, String carrierName) {
        log.info("【订单服务】开始为订单[{}]创建物流单，承运商: {}", order.getOrderNumber(), carrierName);
        try {
            Map<String, Object> shipmentRequest = new HashMap<>();
            shipmentRequest.put("orderId", order.getOrderNumber());
            shipmentRequest.put("customerId", order.getCustomerId());
            shipmentRequest.put("shippingMethod", order.getShippingMethod()); // 从订单获取配送方式
            shipmentRequest.put("carrierName", carrierName); // 使用前端选择的承运商
            
            // 预计送达时间（当前时间加3天）
            LocalDateTime estimatedDeliveryDate = LocalDateTime.now().plusDays(3);
            shipmentRequest.put("estimatedDeliveryDate",
                    estimatedDeliveryDate.format(DateTimeFormatter.ISO_DATE_TIME));

            // 收发地址信息
            shipmentRequest.put("originAddress", "广州市天河区天河路123号");
            shipmentRequest.put("destinationAddress", order.getShippingAddress());

            // 包裹信息
            shipmentRequest.put("packageDimensions", "30x20x15cm");
            shipmentRequest.put("packageWeight", 2.5);
            shipmentRequest.put("notes", "订单编号: " + order.getOrderNumber());

            log.info("【订单服务】远程调用物流服务: POST /api/shipment, 参数: {}", shipmentRequest);
            Result<?> result = logisticsClient.createShipment(shipmentRequest);
            if (result.getCode() != 200) {
                log.error("【订单服务】创建物流单失败: {}", result.getMessage());
                return false;
            }

            Map<String, Object> data = (Map<String, Object>) result.getData();
            String trackingNumber = (String) data.get("trackingNumber");
            log.info("【订单服务】订单[{}]物流单创建成功，物流单号: {}", order.getOrderNumber(), trackingNumber);

            return true;
        } catch (Exception e) {
            log.error("【订单服务】创建物流单异常", e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getOrderShipments(String orderId) {
        log.info("【订单服务】开始查询订单[{}]物流信息", orderId);
        try {
            log.info("【订单服务】远程调用物流服务: GET /api/shipment/order/{}", orderId);
            Result<?> result = logisticsClient.getShipmentsByOrderId(orderId);
            if (result.getCode() != 200) {
                log.error("【订单服务】查询物流信息失败: {}", result.getMessage());
                return new HashMap<>();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("shipments", result.getData());
            log.info("【订单服务】订单[{}]物流信息查询成功: {}", orderId, result.getData());
            return response;
        } catch (Exception e) {
            log.error("【订单服务】查询物流信息异常", e);
            return new HashMap<>();
        }
    }
}